<?php

namespace common\models\user;

use Yii;

/**
 * This is the model class for table "{{%user_relation}}".
 *
 * @property int $id 用户ID
 * @property int $user_id 用户ID
 * @property int $to_user_id 关系用户ID
 * @property int $type 关系类型，0关注，-1黑名单，1朋友
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class UserRelation extends \common\db\ActiveRecord {

    use \common\traits\relation\UserData;

    const TYPE_HIDDEN = -1;
    const TYPE_ONE = 0;
    const TYPE_TWO = 1;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_relation}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'to_user_id', 'type', 'created_at', 'updated_at'], 'integer'],
            ['user_id', 'compare', 'compareAttribute' => 'to_user_id', 'operator' => '!='],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => '用户ID',
            'user_id' => '用户ID',
            'to_user_id' => '关系用户ID',
            'type' => '关系类型，0关注，-1黑名单，1朋友',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function afterDelete() {
        parent::afterDelete();
        $relation = $this->findOne([
            'user_id' => $this->to_user_id,
            'to_user_id' => $this->user_id,
        ]);
        if ($relation && $relation->type == static::TYPE_TWO) {
            $relation->type = static::TYPE_ONE;
            $relation->save();
        }
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);
        $relation = $this->findOne([
            'user_id' => $this->to_user_id,
            'to_user_id' => $this->user_id,
        ]);
        if ($relation) {
            $type = $relation->type;
            if ($insert) {
                //这里是新增数据
                if ($this->type == static::TYPE_HIDDEN && $relation->type == static::TYPE_TWO) {
                    //用户1拉黑用户2
                    $type = static::TYPE_ONE;
                } elseif ($this->type == static::TYPE_ONE && $relation->type == static::TYPE_ONE) {
                    //用户1关注用户2
                    $type = static::TYPE_TWO;
                }
            } else {
                //这里是更新数据
                if ($this->type == static::TYPE_TWO && $relation->type == static::TYPE_ONE) {
                    //用户2被用户1关注
                    $type = static::TYPE_TWO;
                } elseif ($this->type == static::TYPE_HIDDEN && $relation->type == static::TYPE_TWO) {
                    //用户2被用户1拉黑
                    $type = static::TYPE_ONE;
                }
            }
            if ($type != $relation->type) {
                $relation->type = $type;
                $relation->save();
            }
        }
    }

}
